const regeneratorRuntime = getApp().globalData.regeneratorRuntime;
const leadservice = require('../../../apiservice/lead/leadservice');
const screenresultservice = require('../../../apiservice/screen/screenresultservice');
const LAST_CONNECTED_DEVICE = 'last_connected_device';
const printUuid = '0000180F-0000-1000-8000-00805F9B34FB'; //蓝牙打印机设备uuid

function inArray(arr, key, val) {
	for (let i = 0; i < arr.length; i++) {
		if (arr[i][key] === val) {
			return i
		}
	}
	return -1
}

module.exports = Behavior({
	behaviors: [],
	properties: {},
	data: {},
	methods: {

		openBluetoothAdapter() {
			let that = this;
			wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
				title: '加载中',
				icon: 'loading'
			});
			if (!wx.openBluetoothAdapter) {
				wx.hideLoading();
				wx.showModal({
					title: '提示',
					content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
					showCancel: false
				});
				return
			}
			wx.openBluetoothAdapter({
				success: (res) => {
					console.log('openBluetoothAdapter success', res)
					setTimeout(function() {
						wx.showLoading();
						that.startBluetoothDevicesDiscovery();
					}, 50);
				},
				fail: (res) => {
					wx.hideLoading();
					console.log('openBluetoothAdapter fail', res);
					if (res.errCode === 10001) {
						wx.showModal({
							title: '错误',
							content: '未找到蓝牙设备, 请打开蓝牙后重试。',
							showCancel: false
						})
						wx.onBluetoothAdapterStateChange((res) => {
							console.log('onBluetoothAdapterStateChange', res)
							if (res.available) {
								// 取消监听，否则stopBluetoothDevicesDiscovery
								// 后仍会继续触发onBluetoothAdapterStateChange，
								// 导致再次调用startBluetoothDevicesDiscovery
								wx.onBluetoothAdapterStateChange(() => {});
								this.startBluetoothDevicesDiscovery();
							}
						})
					}
				}
			})
			wx.onBLEConnectionStateChange((res) => {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				console.log('onBLEConnectionStateChange',
					`device ${res.deviceId} state has changed, connected: ${res.connected}`)
				this.setData({
					connected: res.connected
				})
				if (!res.connected) {
					wx.showModal({
						title: '错误',
						content: '蓝牙连接已断开',
						showCancel: false
					})
				}
			});
		},

		//取蓝牙设备状态
		getBluetoothAdapterState() {
			let that = this;
			wx.getBluetoothAdapterState({
				success: (res) => {
					console.log('getBluetoothAdapterState', res)
					if (res.discovering) {
						that.onBluetoothDeviceFound();
					} else if (res.available) {
						setTimeout(function() {
							wx.showLoading();
							that.startBluetoothDevicesDiscovery();
						}, 50);
					}
				},
				complete() {
					wx.hideLoading()
				},
			})
		},

		//搜寻蓝牙设备
		startBluetoothDevicesDiscovery() {
			let that = this;
			if (this._discoveryStarted) {
				wx.hideLoading();
				return
			}
			this._discoveryStarted = true
			wx.startBluetoothDevicesDiscovery({
				success: (res) => {
					console.log('startBluetoothDevicesDiscovery success', res)
					setTimeout(function() {
						wx.showLoading({
							title:'搜索设备...'
						})
						that.onBluetoothDeviceFound()
					}, 50);
				},
				complete() {
					wx.hideLoading();
				},
				fail: (res) => {
					console.log('startBluetoothDevicesDiscovery fail', res);
					wx.hideLoading();
				}
			})
		},

		//停止搜寻蓝牙设备
		stopBluetoothDevicesDiscovery() {
			wx.stopBluetoothDevicesDiscovery({
				complete: () => {
					console.log('stopBluetoothDevicesDiscovery')
					this._discoveryStarted = false
				}
			})
		},

		//搜寻到蓝牙设备绑定列表
		onBluetoothDeviceFound() {
			wx.onBluetoothDeviceFound((res) => {
				//debugger;
				res.devices.forEach(device => {
					if (!device.name && !device.localName) {
						return
					}
					const foundDevices = this.data.devices
					const idx = inArray(foundDevices, 'deviceId', device.deviceId)
					const data = {}
					if (idx === -1) {
						data[`devices[${foundDevices.length}]`] = device
					} else {
						data[`devices[${idx}]`] = device
					}
					this.setData(data)
				});
				wx.hideLoading();
			})
		},

		//建立设备链接设备ID设备name
		_createBLEConnection(deviceId, name) {
			let that = this;
			wx.showLoading()
			wx.createBLEConnection({
				deviceId,
				success: () => {
					console.log('createBLEConnection success');
					this.setData({
						connected: true,
						name,
						deviceId,
					})

					setTimeout(function() {
						wx.showLoading();
						that.getBLEDeviceServices(deviceId);
					}, 100);

					wx.setStorage({
						key: LAST_CONNECTED_DEVICE,
						data: name + ':' + deviceId
					})
				},
				complete() {
					wx.hideLoading()
				},
				fail: (res) => {
					console.log('createBLEConnection fail', res)

					wx.closeBLEConnection({
						deviceId: deviceId
					})

				}
			})
			this.stopBluetoothDevicesDiscovery()
		},

		getBLEDeviceServices(deviceId) {

			wx.getBLEDeviceServices({
				deviceId,
				success: (res) => {
	              debugger;
					console.log('getBLEDeviceServices', res)
					for (let i = 0; i < res.services.length; i++) {

						if (res.services[i].isPrimary) {
						
							if (res.services[i].uuid === printUuid) {
								//if(i === 2){
								//debugger;
								//console.log(res.services[i].uuid);
								this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)

								return
							}
						}
					}
				},
				complete() {
					wx.hideLoading()
				},
				fail: (res) => {
					debugger;
					console.log("获取蓝牙服务失败：" + JSON.stringify(res))
				}
			})
		},

		getBLEDeviceCharacteristics(deviceId, serviceId) {
			wx.getBLEDeviceCharacteristics({
				deviceId,
				serviceId,
				success: (res) => {
					console.log('getBLEDeviceCharacteristics success', res.characteristics)
					// 这里会存在特征值是支持write，写入成功但是没有任何反应的情况
					// 只能一个个去试
					for (let i = 0; i < res.characteristics.length; i++) {
						const item = res.characteristics[i]
						if (item.properties.write && item.properties.read) {
							//debugger;
							this.setData({
								canWrite: true
							})
							this._deviceId = deviceId;
							this._serviceId = serviceId;
							this._characteristicId = item.uuid;
							break;
						}
					}
				},
				fail(res) {
					console.error('getBLEDeviceCharacteristics', res)
				}
			})
		},

		getStudentInfo: async function(leadid, that) {
			try {
				//debugger;
				let result = await leadservice.QueryStudentInfoById(leadid);
				that.setData({
					studentInfo: result.data
				})
				wx.hideLoading();
			} catch (e) {
				//TODO handle the exception
			} finally {
				wx.hideLoading();
			}
		},

		GetScreenResultsByScreenIdAndCustomerId: async function(scid, leadid, that) {
			try {
				//var that = this;
				let scResult = await screenresultservice.GetScreenResultByScidAndCustomerId(scid, leadid);
				//debugger;
				let nakedEyeshow = scResult.data.nakedEye ? true : false
				let correctEyeshow = scResult.data.correctEye ? true : false
				let scjudgeshow = scResult.data.scjudgeResult && scResult.data.scjudgeResult.length > 0 ? true : false
				let adviseshow = scResult.data.advise ? true : false
				let refractiveexaminationshow = scResult.data.refractiveexamination ? true : false
				let dioptertestshow = scResult.data.dioptertest ? true : false
				that.setData({
					nakedEye: scResult.data.nakedEye ? scResult.data.nakedEye : {},
					nakedEyeshow: nakedEyeshow,
					correctEye: scResult.data.correctEye ? scResult.data.correctEye : {},
					correctEyeshow: correctEyeshow,
					scjudgeResult: scResult.data.scjudgeResult ? scResult.data.scjudgeResult : {},
					scjudgeshow: scjudgeshow,
					advise: scResult.data.advise ? scResult.data.advise : '',
					adviseshow: adviseshow,
					refractiveexamination: scResult.data.refractiveexamination ? scResult.data.refractiveexamination : '',
					refractiveexaminationshow: refractiveexaminationshow,
					dioptertest: scResult.data.dioptertest ? scResult.data.dioptertest : '',
					dioptertestshow: dioptertestshow,
				})
				//debugger;
				console.log('筛查结果', scResult.data);

				if (that.data.schoolId) {
					that.getStudentInfo(leadid, that)
				} else {
					wx.hideLoading();
				}
			} catch (e) {
				//TODO handle the exception
			} finally {
				//wx.hideLoading();
			}

		},

	}
});
